package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
@Api(tags = "套餐相关接口")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    /**
     * 保存套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping()
    @ApiOperation(value = "新增套餐接口")
    @CacheEvict(value = "setmealCache", allEntries = true)// 清楚setmealCache下所有套餐缓存信息
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info(setmealDto.toString());
        setmealService.saveWithDish(setmealDto);
        return R.success("套餐添加成功");
    }

    /**
     * 分页查询套餐信息
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询接口")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> dtoPage = new Page<>();
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, Setmeal::getName, name);
        lqw.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo, lqw);
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map(item -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据分类id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //分类名称
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 删除套餐信息
     *
     * @param ids
     * @return
     */
    @DeleteMapping()
    @ApiOperation(value = "套餐删除接口")
    @CacheEvict(value = "setmealCache", allEntries = true)// 清楚setmealCache下所有套餐缓存信息
    public R<String> delete(@RequestParam("ids") List<Long> ids) {
        log.info("删除的套餐信息:{}", ids);
        setmealService.removeWithDish(ids);
        return R.success("删除成功");
    }

    /**
     * 根据id查询套餐信息,回显套餐信息
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    @ApiOperation(value = "套餐条件查询接口")
    public R<SetmealDto> get(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setmealCache", allEntries = true)// 清楚setmealCache下所有套餐缓存信息
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        setmealService.updateWithDish(setmealDto);
        return R.success("修改成功");
    }

    /**
     * 修改套餐售卖状态
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache", allEntries = true)// 清楚setmealCache下所有套餐缓存信息
    public R<String> status(@PathVariable int status, @RequestParam("ids") List<Long> ids) {
        log.info("需要修改的套餐为:{}", ids.toString());
        List<Setmeal> dishes = setmealService.listByIds(ids);
        for (Setmeal setmeal : dishes) {
            setmeal.setStatus(status);
        }
        setmealService.updateBatchById(dishes);
        return R.success("销售状态修改成功");
    }

    /**
     * 查询套餐信息
     *
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        //查询前端页面传过来的套餐数据,根据id查询套餐
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //查询分类id
        lqw.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        //查询状态
        lqw.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        //排序
        lqw.orderByDesc(Setmeal::getUpdateTime);
        //用list方法查询所有套餐
        List<Setmeal> list = setmealService.list(lqw);
        return R.success(list);
    }

    /**
     * 查询套餐菜品信息
     *
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<List<SetmealDishDto>> setmealDish(@PathVariable Long id) {
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(lqw);
        //获取图片信息
        //已有setmealdish的list,可以遍历list
        //取到setmealdish中的dishid,也就可以用dishid
        //从dish表中获取到dish的image字符串
        //把字符串给到setmealdishDto,
        //dto中也应该只多加了一个image字符串
        List<SetmealDishDto> setmealDishDtoList = list.stream().map(item -> {
            Dish dish = dishService.getById(item.getDishId());
            SetmealDishDto setmealDishDto = new SetmealDishDto();
            BeanUtils.copyProperties(item, setmealDishDto);
            if (dish != null) {
                setmealDishDto.setImage(dish.getImage());
            }
            return setmealDishDto;
        }).collect(Collectors.toList());
        return R.success(setmealDishDtoList);
    }
}